import React, { useEffect, useState, useRef } from 'react'
import { Steps, Button, Form, Input, Select, message, notification, Descriptions } from 'antd'
import style from './newsUpdate.module.css'
import NewEditor from '@/components/news-manage/NewsEditor'
import { useNavigate } from 'react-router'
import { useParams } from 'react-router-dom'
import { getNewsInfoApi, updateNewsApi } from '@/api/news'
import { getCategoriesApi } from '@/api/categories'

const { Option } = Select

function NewsUpdate() {
  // 路由跳转
  const navigate = useNavigate()
  // 当前是第几部的状态
  const [current, setCurrent] = useState(0)
  // 新闻标题列表
  const [categoryList, setCategoryList] = useState([])
  // 设置当前表单
  const [formInfo, setFormInfo] = useState({})
  // 获取编辑器的内容
  const [content, setContent] = useState('')
  // 获取详情
  const [info, setInfo] = useState({})
  // 使用ref获取表单
  const NewsForm = useRef(null)
  const params = useParams()

  // 获取新闻类型列表
  useEffect(() => {
    getNewsInfo()
    getCategoriesApi().then(res => {
      setCategoryList(res)
    })
  }, [])

  // 获取信息详情
  const getNewsInfo = () => {
    getNewsInfoApi(params.id).then(res => {
      setInfo(res)
      let { title, categoryId, content } = res
      NewsForm.current.setFieldsValue({
        title: title,
        categoryId: categoryId
      })
      setContent(content)
    })
  }

  // 到下一步
  const handleNext = () => {
    if (current === 0) {
      // 检查表单时否填写完整
      NewsForm.current.validateFields().then(res => {
        setFormInfo(res)
        setCurrent(current + 1)
      })
        .catch(err => {
          console.log(err)
        })
    } else {
      if (content === '' || content.trim() == '<p></p>') {
        message.error('请输入新闻内容')
      } else {
        setCurrent(current + 1)
      }
    }
  }

  // 下一步
  const handlePrevious = () => {
    setCurrent(current - 1)
  }

  // 提交
  const handleSave = (auditState) => {
    // 通过axios发送请求，auditState决定是否审核或者存草稿
    const data = {
      ...info,
      ...formInfo,
      'content': content,
      'auditState': auditState
    }
    updateNewsApi(params.id, data).then(() => {
      // 跳转到草稿箱或者审核列表
      navigate(auditState === 0 ? '/news-manage/draft' : '/audit-manage/list')
      // 通知用户
      notification.info({
        message: '通知',
        description: `您可以到${auditState === 0 ? '草稿箱' : '审核管理'}中查看新闻`,
        placement: 'bottomRight'
      })
    })
  }

  return (
    <div>
      <Descriptions
        extra={<Button onClick={() => navigate(-1)} type="primary">返回</Button>}
        title="更新新闻"
      />
      <Steps current={current} items={[
        {
          title: '基本信息',
          description: '新闻标题,新闻分类'
        },
        {
          title: '新闻内容',
          description: '新闻主体内容'
        },
        {
          title: '新闻提交',
          description: '保存草稿或者提交审核'
        }
      ]}>
      </Steps>
      <div style={{ marginTop: '50px' }}>
        <div className={current === 0 ? '' : style.activate}>
          <Form
            autoComplete="off"
            initialValues={{
              remember: true
            }}
            labelCol={{
              span: 4
            }}
            name="basic"
            ref={NewsForm}
            wrapperCol={{
              span: 20
            }}>
            <Form.Item
              label="新闻标题"
              name="title"
              rules={[
                {
                  required: true,
                  message: '请输入新闻标题'
                }
              ]}>
              <Input/>
            </Form.Item>

            <Form.Item
              label="新闻分类"
              name="categoryId"
              rules={[
                {
                  required: true,
                  message: '请选择新闻分类'
                }
              ]}>
              <Select>
                {
                  categoryList.map(item => {
                    return <Option key={item.id} value={item.id}>{item.value}</Option>
                  })
                }
              </Select>
            </Form.Item>
          </Form>
        </div>
        <div className={current === 1 ? '' : style.activate}>
          <NewEditor content={content} getContext={(value) => {
            // 通过回调获取编辑器的内容
            setContent(value)
          }}/>
        </div>
        <div className={current === 2 ? '' : style.activate}></div>
      </div>
      <div style={{ marginTop: '50px' }}>
        {current === 2 &&
          <span>
            <Button onClick={() => handleSave(0)} type="primary">保存草稿</Button>
            <Button danger onClick={() => handleSave(1)}>提交审核</Button>
          </span>
        }
        {current < 2 && <Button onClick={() => { handleNext() }} type="primary">下一步</Button>}
        {current > 0 && <Button onClick={() => { handlePrevious() }}>上一步</Button>}
      </div>
    </div>
  )
}

export default NewsUpdate